package online.chenlu.blog.advice;


import online.chenlu.blog.core.NoFoundException;
import online.chenlu.blog.core.Result;
import online.chenlu.blog.core.ServiceException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Describe controller 增强器
 * @Author chenlu
 * @Version V1.0
 * @Date 2019/3/28.
 */
@RestControllerAdvice
public class MyControllerAdvice {

    /**
     * 全局异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result errorHandler(Exception ex) {
        return Result.failure(ex.getMessage());
    }

    /**
     * 拦截捕捉自定义异常 MyException.class
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ServiceException.class)
    public Result myErrorHandler(ServiceException ex) {
        return Result.failure("系统异常");
    }

    @ExceptionHandler(value = NoFoundException.class)
    public ModelAndView myErrorHandler(NoFoundException ex) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("code", 404);
        modelAndView.addObject("msg", "找不到资源");
        return modelAndView;
    }

}